<?php

/*
class Container, a component which can contain other components
Copyright (C) 2011  Petr Čermák

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

require_once 'ViewHandler.php';

class Container extends ViewHandler{

    private $components = array();

    //protected function process(){parent::process();}
    //protected function processActions(){parent::processActions();}

    //public function processRequest(){parent::processRequest();}

    public function initialize(){
        parent::initialize();
        foreach($this->getComponents() as $name => $component){
            if($component->isEnabled()){
                $component->initialize();
                if($component instanceof Router)
                    $component->updateCurrentComponent();
            }
        }
    }

    /**
     * Gets all added components.
     * @return array added components
     */
    public function getComponents(){return $this->components;}

    /**
     * Gets component identified by the provided name.
     * @param string the component name
     */
    public function getComponent($name){
        if(array_key_exists($name, $this->components)){
            $this->components[$name]->initialize();
            return $this->components[$name];
        }
        return null;
    }

    /**
     * Checks if component of provided name exists in the container.
     * @param string the component name
     */
    public function hasComponent($name){
        return array_key_exists($name, $this->components);
    }

    /**
     * Adds a new component identified by provided name
     * to the container if it's not already added.
     * @param string the component name
     * @param Component the component to be added
     */
    public function add($name, Component $component){
        Checker::checkString($name);
        if(array_key_exists($name, $this->components))
            unset($this->components[$name]);
        //if(!array_key_exists($name, $this->components)){
            $component->setName($name);
            $component->setOwner($this);
            //$component->initialize();
            $this->components[$name] = $component;
        //}
    }

}
?>
